#define _CRT_SECURE_NO_WARNINGS 1
#include"QuickSort.h"
void InsertSort(int* a, int size)
{
	for(int i = 0;i<size-1;i++)
	{
		int end = i;
		int tmp = a[end + 1];
		while (end >= 0)
		{
			if (tmp < a[end])
			{
				a[end + 1] = a[end];
				end--;
			}
			else
				break;
		}
		a[end + 1] = tmp;
	}
}

void PrintArray(int* a, int size)
{
	for (int i = 0; i < size; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}

void ShellSort(int* a, int size)
{
	int gap = size;
	while(gap>1)
	{
		gap = gap / 3 + 1;
		for (int i = 0; i < size - gap; i++)
		{
			int end = i;
			int tmp = a[end + gap];
			while (end >= 0)
			{
				if (tmp < a[end])
				{
					a[end + gap] = a[end];
					end -= gap;
				}
				else
					break;
			}
			a[end + gap] = tmp;
		}
		
	}
}

void swap(int* a, int* b)
{
	int c = *a;
	*a = *b;
	*b = c;
}
int GetMidi(int* a, int begin, int end)
{
	int midi = (begin + end) / 2;
	if (a[begin] > a[end])
	{
		if (a[end] > a[midi])
			return end;
		else
			return midi;
	}
	if (a[end] > a[begin])
	{
		if (a[begin] > a[midi])
			return begin;
		else
			return midi;
	}
	if (a[midi] > a[begin])
	{
		if (a[begin] > a[end])
			return begin;
		else
			return end;
	}

}
void QuickSort(int* a, int begin,int end)
{
	if (begin>=end)
	{
		return;
	}

	int midi = GetMidi(a, begin, end);
	swap(&a[begin], &a[midi]);

	int left = begin;
	int right = end ;

	int keyi = begin;

	while (left < right)
	{
		while (left < right && a[right] >= a[keyi])
		{
			right--;
		}

		while (left < right && a[left] <= a[keyi])
		{
			left++;
		}

		swap(&a[left], &a[right]);
	}
	swap(&a[left], &a[keyi]);

	keyi = left;
	QuickSort(a, begin,keyi-1);


	QuickSort(a, keyi+1,end);

}
void MyQuickSort(int* a, int size)
{
	if (size == 1||size == 0)
	{
		return;
	}
	int left = 0;
	int right = size -1;

	int key = 0;

	while (left < right)
	{
		while (left < right && a[right] >= a[key])
		{
			right--;
		}

		while (left < right && a[left] <= a[key])
		{
			left++;
		}
		swap(&a[left], &a[right]);
	}
	swap(&a[left], &a[key]);

	key = left;
	MyQuickSort(a,key);


	MyQuickSort(a+key+1, size - key -1);

}